import { useUserStore } from "@/store"

const TOKEN = 'TOKEN'

const loginFailure = () => {
  uni.showToast({title: '登录失效', icon: 'none'}).then(() => {

    const page = getCurrentPages().reverse()[0]
    
    uni.redirectTo({
      url: '/pages/login/index?path=' + page.route + '&query=' + JSON.stringify(page.options)
    })
  })
}

export const tabbarPath = [
  'pages/keyword/index',
  'pages/diary/index',
  'pages/square/index',
  'pages/my/index'
]

interface Params {
  params?: any,
  url?: string,
  method: 'GET' | 'POST' | 'PUT' | 'DELETE'
  responseType?: '',
  baseURL?: string
}

// const BASEURL = import.meta.env.MODE === 'development' ? 'http://local.luojigou.vip:8888' : 'https://open.api.luojigou.vip'
// export const BASEURL = import.meta.env.MODE == 'development' ? 'http://101.126.76.198:18085' : 'https://jy-health.pro/api'
export const BASEURL = import.meta.env.MODE == 'development' ? 'http://localhost:8099' : 'https://daily-note.wordssay.cn'
// export const BASEURL = import.meta.env.MODE == 'development' ? 'http://daily-note.wordssay.cn' : 'http://daily-note.wordssay.cn'

export const avatarUrl = BASEURL + `/dailyNote/api/login`
export const request = async <T>(
  params: Params
) => {
  let data = params.params || {};
  let url = (params.baseURL ? params.baseURL: BASEURL) + params.url;
  let method = params.method
  let responseType = params.responseType

  let token = useUserStore().token

  const response = await new Promise(resolve => {
     uni.request({
      url: url,
      method: method,
      data: data,
      header: {
        'content-type': 'application/json',
        token: token
      },
      responseType,
      success: res => resolve(res.data)
    })
  }) as any
  

  if (response.status === 500 ) {
    uni.showToast({title: response.msg, icon: 'none'})
  } else if (response.status === 401 || response.status === 304) {
    loginFailure()
  }

  return response as API.Response<T>
  
}


